package com.sts.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sts.dto.TicketCommentDTO;
import com.sts.entity.TicketComment;
import com.sts.mapper.TicketCommentMapper;
import com.sts.mapper.TicketMapper;
import com.sts.service.TicketCommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class TicketCommentServiceImpl implements TicketCommentService {

    private final TicketCommentMapper commentMapper;
    private final TicketMapper ticketMapper;
    @Override
    public Long addComment(TicketCommentDTO dto, Long authorId) {
        // ✅ 校验工单是否存在
        if (ticketMapper.selectById(dto.getTicketId()) == null) {
            throw new IllegalArgumentException("工单不存在，无法添加评论");
        }

        TicketComment c = TicketComment.builder()
                .ticketId(dto.getTicketId())
                .parentId(dto.getParentId())
                .content(dto.getContent())
                .authorId(authorId)
                .createdAt(LocalDateTime.now())
                .build();
        commentMapper.insert(c);
        return c.getId();
    }
    @Override
    public TicketCommentDTO detail(Long id) {
        TicketComment po = commentMapper.selectById(id);
        return po == null ? null : BeanUtil.copyProperties(po, TicketCommentDTO.class);
    }
    @Override
    public List<TicketCommentDTO> listByTicket(Long ticketId) {
        LambdaQueryWrapper<TicketComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TicketComment::getTicketId, ticketId)
                .orderByAsc(TicketComment::getCreatedAt);
        return commentMapper.selectList(wrapper)
                .stream()
                .map(e -> BeanUtil.copyProperties(e, TicketCommentDTO.class))
                .collect(Collectors.toList());
    }
    @Override
    public void deleteComment(Long id, Long operatorId) {
        commentMapper.deleteById(id);
    }
}